<?php
namespace app\manage\controller;
use think\Db;

class AnalysisGameChange extends Base
{
    public function index(){
        if(request()->isAjax() || input('?export')){
            $plat = input('plat');
            $gameId = input('game_id');
            $startTime = strtotime(input('date'));
            $endTime = $startTime+86399;
            $endTime2 = $startTime+(86400*input('range'))-1;
            $year = date('Y', $startTime);

            $where = 1;
            //游戏条件
            !empty($gameId) && $where .= " && game_id={$gameId}";

            //平台条件
            if($plat=='cps'){
                $where .= " && channel_id='1000'";
            }else if($plat=='sdk'){
                $where .= " && channel_id>='5000'";
            }else{
                $where .= '';
            }

            $whereAdd = $where .  " && bond_time between {$startTime} AND {$endTime}";
            $whereActive = $where . " && in_time between {$startTime} AND {$endTime2}";
            $whereOrder = $where . " && order_time between {$startTime} AND {$endTime2} AND debug=0";
            $wherePay = $where . " && pay_time between {$startTime} AND {$endTime2} AND debug=0 AND pay_result=1";

            $selectAdd = Db::name('GameUserY_'.$year)
                ->field("distinct game_id,my_user_id")
                ->where($whereAdd)
                ->select();

            $m1 = date('Ym', $startTime);
            $m2 = date('Ym', $endTime2);
            if($m2>date('Ym')){
                $this->layTable();
            }

            if($m1==$m2){
                $selectActive = Db::name('GameUserLogM_'.$m1)
                    ->field("distinct game_id,my_user_id")
                    ->where($whereActive)
                    ->select();
            }else{
                $field = "game_id,my_user_id";
                $subQuery = Db::name('GameUserLogM_'.$m1)
                    ->field($field)
                    ->where($whereActive)
                    ->union("select {$field} from sdk_game_user_log_m_{$m2} where ({$whereActive})", true)
                    ->buildSql();

                $selectActive = Db::table($subQuery.' m')
                    ->field('distinct game_id,my_user_id')
                    ->select();
            }

            $selectOrder = Db::name('PayOrderY_'.$year)
                ->field("distinct game_id,my_user_id")
                ->where($whereOrder)
                ->select();
            $selectPay = Db::name('PayOrderY_'.$year)
                ->field("distinct game_id,my_user_id")
                ->where($wherePay)
                ->select();

            //新增转创角
            $changeActive = $this->arrayChange($selectAdd, $selectActive);

            //创角转下单
            $changeOrder = $this->arrayChange($changeActive['my_user_id'], $selectOrder);

            //下单转支付
            $changePay = $this->arrayChange($changeOrder['my_user_id'], $selectPay);

            $selectMoney = [];
            if($changePay['my_user_id']){
                $myUserIdStr = '';
                foreach ($changePay['my_user_id'] as $k=>$v){
                    $myUserIdStr .= $v['my_user_id'] . ',';
                }
                $myUserIdStr = rtrim($myUserIdStr, ',');

                $whereMoney = $wherePay . " && my_user_id in ({$myUserIdStr})";
                $selectMoney = Db::name('PayOrderY_'.$year)
                    ->field("game_id, sum(total_price) as total_price")
                    ->where($whereMoney)
                    ->group('game_id')
                    ->select();
            }

            //汇总
            $data = [];
            foreach ($selectAdd as $k=>$v){
                if(isset($data[$v['game_id']]['game_add'])){
                    $data[$v['game_id']]['game_add'] += 1;
                }else{
                    $data[$v['game_id']]['game_add'] = 1;
                }
            }
            foreach ($changeActive['count'] as $k=>$v){
                $data[$k]['game_active'] = $v;
            }
            foreach ($changeOrder['count'] as $k=>$v){
                $data[$k]['order_number'] = $v;
            }
            foreach ($changePay['count'] as $k=>$v){
                $data[$k]['pay_number'] = $v;
            }
            foreach ($selectMoney as $k=>$v){
                $data[$v['game_id']]['pay_money'] = $v['total_price']/100;
            }

            $allData = [];
            $gameIdName = model('Game')->gameIdName();
            foreach ($data as $k=>$v){
                $allData[] = [
                    'date' => date('Y-m-d', $startTime),
                    'game_id' => $k,
                    'game_name' => isset($gameIdName[ $k ]) ? $gameIdName[ $k ] : '',
                    'game_add' => isset($v['game_add']) ? $v['game_add'] : '0',
                    'game_active' => isset($v['game_active']) ? $v['game_active'] : '0',
                    'order_number' => isset($v['order_number']) ? $v['order_number'] : '0',
                    'pay_number' => isset($v['pay_number']) ? $v['pay_number'] : '0',
                    'pay_money' => isset($v['pay_money']) ? $v['pay_money'] : '0',
                ];
            }

            //导出
            if(input('?export')){
                array_unshift($allData, ['日期', '游戏ID', '游戏名称', '游戏新增', '游戏活跃', '下单人数', '付费人数', '付费金额']);
                exportExcel($allData, input('date').'转化率', input('date').'转化率');
            }

            $this->layTable(0, '游戏转化率', $allData, count($allData));
        }else{
            $date = date('Y-m-d', time()-(86400*2));
            return view('', ['date'=>$date]);
        }
    }

    private function arrayChange($arrAdd, $arrChange){
        $newAdd = [];
        foreach ($arrChange as $k=>$v){
            $newAdd[$v['game_id']][$v['my_user_id']] = 1;
        }

        $count = [];
        $myUserId = [];
        foreach ($arrAdd as $k=>$v){
            if(isset($newAdd[$v['game_id']][$v['my_user_id']])){
                if(isset($count[$v['game_id']])){
                    $count[$v['game_id']] += 1;
                }else{
                    $count[$v['game_id']] = 1;
                }
                $myUserId[] = $v;
            }
        }

        $arrayChange['my_user_id'] = $myUserId;
        $arrayChange['count'] = $count;
        return $arrayChange;
    }

    public function chart(){
        return view();
    }
}
